param(
	[Parameter(Mandatory=$false)]                             
	[string]$inputFile="inputlist.txt",     # the input file to store vdi,domain and fid list
	[Parameter(Mandatory=$false)]                             
	[switch]$inputFileSaved,               # tell if inputfile has been saved, otherwise will popup text to let user enter VDI list.
	[Parameter(Mandatory=$false)]                             
	[switch]$functionInvoked              # tell if script needs to invoke functions
)
$st=get-date
$this_path = Split-Path -Parent ($MyInvocation.MyCommand.Definition) # get the directory of this running script
$parent_path=(get-item $this_path).Parent.FullName
If( !$functionInvoked ){
	. "$parent_path\functions.ps1" # import functions to powershell from functions.ps1
}
If( $inputFile -notlike "*\*"){
    $inputFile="$this_path\$inputFile"
}
$inputlist=Get-Inputlist $inputFile $inputFileSaved
#-------------------------------------------------ITRS Setting Checking------------------------------------------------------------------
$itrs_temppath="$this_path\temp" # used to store each result csv file from end vdi incase the script breaks in the middle of running unexpectedly so that we can check the file and know which ones we have already checked
del "$itrs_temppath\*.csv" -Force -ErrorAction Ignore
del "$this_path\*.csv" -Force -ErrorAction Ignore
New-FileOrFolder $itrs_temppath -d
$itrs_reglist_file="$this_path\to_be_checked_registry.txt" ; New-FileOrFolder $itrs_reglist_file
$itrs_reglist=(get-content $itrs_reglist_file |select -Unique|?{$_.trim() -ne ""})
If( $itrs_reglist -eq $null ){
	Do{ # loop above action if the vdi list is empty 
		write-host "Please save registry key list as below format in opened txt file each line as it's empty and then press enter to continue in powershell console, please press 'Ctrl+C' if you want to quit:
		HKCU:\Control Panel\Desktop\ScreenSaveTimeOut
		HKLM:\Software\Policies\Microsoft\Windows NT\Terminal Services\MaxIdleTime" ; notepad $itrs_reglist_file
		read-host " "
		$itrs_reglist = (get-content $itrs_reglist_file |select -Unique|?{$_.trim() -ne ""})
	}While( $itrs_reglist -eq $null  )
}
$itrs_action={
	param($line,$cnt,$ActionParams)
	try{$vdi,$domain,$fid,$env=$line.split(",").trim()}catch{}
	$itrs_reglist,$itrs_temppath=$ActionParams
	write-host "Processing in $cnt-$vdi for ITRS checking...`n"
	$registries = [ordered]@{"Category/Setting"="$vdi/$fid/$domain"}
	For( $n=0; $n -lt $itrs_reglist.count; $n++ ){
		$item="ITRS/"+$itrs_reglist[$n]
		$registries.Add($item,$null)
	}
	If( $itrs_reglist -imatch "HKCU"){ # check if domain and FID provided for check HKCU registry
		If( [string]::IsNullOrWhiteSpace($fid) -or [string]::IsNullOrWhiteSpace($domain)){
			$registries.Set_Item("Category/Setting","$vdi/$fid-fid not provided/$domain")
			$rst= New-Object PSObject -Property $registries
			Write-Host -ForegroundColor Red "$cnt-$vdi FID Not Provided"
			return $rst
		}else{
			If( !(Check-FIDExistence $domain $fid) ){ # check if given FID exists in given domain 
				$registries.Set_Item("Category/Setting","$vdi/$fid-$fid was not found in domain/$domain")
				$rst= New-Object PSObject -Property $registries
				Write-Host -ForegroundColor Red "$cnt-$vdi FID Not Provided"
				return $rst
			}
		}
	}
	If(Test-Connection $vdi -quiet -count 1 -ErrorAction Ignore){ # write-host "Checking if $vdi is online"
		try{
			test-path "\\$vdi\c$\" -ErrorAction Stop 1>$null
		}catch{
			If($_.exception -like "*Access is denied*"){$registries.Set_Item("Category/Setting","$vdi/$fid/$domain Access denied")}
			$rst= New-Object PSObject -Property $registries
			return $rst
		}
		$sid = (New-Object System.Security.Principal.NTAccount("$domain\$fid")).Translate([System.Security.Principal.SecurityIdentifier]).value
		Function Get-Regvalue($registry,$vdi,$sid){
			If( $registry.Substring($registry.Length-1) -eq "\"){$registry=$registry.Substring(0,$registry.Length-1)}
			$registry=$registry -replace("HKCU:?\\","\\$vdi\HKU\$sid\") -replace("HKLM:?\\","\\$vdi\HKLM\") 2>$null
			$index_of_lastslash=$registry.LastIndexOf('\');$key=$registry.Substring(0,$index_of_lastslash);$value=$registry.Substring($index_of_lastslash+1)
			$rst=(reg query $key /v $value) -imatch $value 2>$null
			If($rst -ne $null){
				$rst=Switch -regex ($rst){
				    "REG_SZ"{
						$reg_value=($_ -split("REG_SZ"))[-1].trim()
						If($value -imatch "legalnoticecaption|legalnoticetext" -and $reg_value.length -gt 0){"Y"}else{$reg_value} ; break
					}
				    "REG_DWORD"  {[convert]::toint32(($_ -split("REG_DWORD"))[-1].trim(),16) ; break}
					"REG_QWORD"  {[convert]::toint64(($_ -split("REG_QWORD"))[-1].trim(),16) ; break}
				    "REG_BINARY" {($_ -split("REG_BINARY"))[-1].trim()}
				}
			}else{$rst= "No such value/key"}
			return $rst
		}
		For( $n=0; $n -lt $itrs_reglist.count; $n++ ){
			$item="ITRS/"+$itrs_reglist[$n]
			$registries.Set_Item($item,(Get-Regvalue $itrs_reglist[$n] $vdi $sid))
		}
	}else{
		$registries.Set_Item("Category/Setting","$vdi-invalid vdi name or offline/$fid/$domain")
	}
	$rst= New-Object PSObject -Property $registries
	Write-Host -ForegroundColor Yellow "----$cnt-$vdi Done checking ITRS registry info----`n"
	$rst|Export-Csv -Path "$itrs_temppath\$vdi-itrs.csv" -UseCulture -NoTypeInformation -Encoding UTF8 -Force -ErrorAction Ignore
	return $rst
}
$itrs_registries = Start-BulkThreads $inputlist $itrs_action $itrs_reglist,$itrs_temppath -maxCnt 100|sort "Category/Setting"
Export-Result $itrs_registries "ITRS Registries" "$this_path\itrs.csv" ([math]::Round(((get-date)-$st).totalseconds))
